const crypto = require("crypto");

module.exports = function(lab) {
    return {

        /**
         * @apiDefine TypeDefineTrader
         * @apiSuccess (result) {String} id 经销商Id
         * @apiSuccess (result) {String} trader_number 经销商编号
         * @apiSuccess (result) {String} trader_name 经销商名称
         * @apiSuccess (result) {String} trader_area 经销商所在地区
         * @apiSuccess (result) {String} trader_address 办公地址
         * @apiSuccess (result) {String} trader_contact 联系人
         * @apiSuccess (result) {Number} trader_contact_phone 联系电话
         */

        // slime_traders 处理这个对象， 和以前一样，需要把SKU进行复制
        // 参数不正确全部用@lab.errors.object_not_found;
        // 有不明白的地方，网上问我!
        @importTrader: function(ouid, { number, name, area, address, contact, phone, account, password }) {

            return lab.snapshot(function(snapshot) {

                return snapshot.sqlite.find("slime_traders", {
                    "trader_number": number,
                    "ouid": ouid
                }).then(function(result) {

                    let existingTraderData;

                    if (result.records.length) {
                        existingTraderData = result.records[0];
                    } else {
                        existingTraderData = {
                            "id": @.uuid(),
                            "ouid": ouid,
                            "trader_number": number
                        }
                        this.pool.newTrader = true;
                    }

                    this.pool.existingTraderData = existingTraderData;

                    snapshot.slime.trader.@saveOrUpdateAccount(existingTraderData, { name, account, password }).pipe(this);

                }).then(function(operator) {

                    var traderData = {};

                    traderData["trader_name"] = name;
                    traderData["trader_area"] = area;
                    traderData["trader_address"] = address;

                    traderData["trader_contact"] = contact;
                    traderData["trader_contact_phone"] = phone;

                    if (operator) {
                        this.pool.existingTraderData.account_id   = operator.id;
                        this.pool.existingTraderData.account_name = operator.account;
                        this.pool.existingTraderData.account_ouid = operator.ouid;
                    }

                    if (this.pool.newTrader) {
                        snapshot.create("slime_traders", @.merge.simple(this.pool.existingTraderData, skuData)).pipe(this);
                    } else {
                        snapshot.update("slime_traders", this.pool.existingTraderData, traderData).pipe(this);
                    }

                }).then(function(savedTrader) {

                    if (savedTrader.account_ouid) {
                        snapshot.slime.trader.@syncSKUBetweenTraders(ouid, savedTrader.account_ouid).resolve(savedTrader).pipe(this);
                    } else {
                        this.next(savedTrader);
                    }

                })
            })
        },

        // 解除ouid 和 trader_ouid之间的关系
        @unbindTrader : function(ouid, trader_ouid){

            return lab.snapshot(function(snapshot) {
                return snapshot.find("slime_traders", {
                    "ouid": trader_ouid,
                    "account_ouid": ouid
                }).then(function(trader) {

                   if (trader.records.length) {

                        snapshot.update("slime_traders", trader.records[0], {
                            account_ouid: null,
                            last_update: Date.now()
                        }).pipe(this);

                   } else {
                        throw @lab.errors.object_not_found;
                   }
                })
            })
        },


        // 绑定套路，初始化数据自己伪造一下。
        // 为ouid 建立 trader_ouid的经销商绑定， 也就是trader_ouid为上级经销商， ouid为下级经销商， 并指定自己的trader_number

        @bindTrader: function(ouid, {trader_ouid, trader_number}) {

            return lab.snapshot(function(snapshot) {

                return @.async(function() {

                    snapshot.find("backend_operation_units", ouid).pipe(this);

                }).then(function(currentOU){

                    if (currentOU){

                        this.pool.currentOU = currentOU;
                        snapshot.find("backend_operation_units", trader_ouid).pipe(this);

                    } else {
                        throw @lab.errors.object_not_found;
                    }

                }).then(function(traderOU) {

                    if (traderOU) {

                        this.pool.traderOU = traderOU;

                        snapshot.sqlite.find("slime_traders", {
                            "ouid"         : traderOU.id,
                            "account_ouid" : ouid,
                        }).pipe(this);

                    } else {
                        throw @lab.errors.object_not_found;
                    }

                }).then(function(result) {

                    if (result.records.length) {

                        if (result.records[0].is_removed){

                            snapshot.update("slime_traders", result.records[0], {
                                is_removed: true,
                                last_update: Date.now()
                            }).pipe(this);

                        } else {
                            this.next(result.records[0]);
                        }

                    } else {

                        if (!trader_number) {
                            throw @lab.errors.invalid_parameters;
                        }
                        // 这里说明， 没有建立绑定关系
                        snapshot.create("slime_traders", {

                            "id"       : @.uuid(),
                            "ouid"     : this.pool.traderOU.id,

                            "trader_number" : trader_number,
                            "trader_name"   : this.pool.currentOU.name,

                            "account_ouid"  : this.pool.currentOU.id,

                            "is_removed": false,
                            "last_update": Date.now()

                        }).then(function(updatedTrader) {

                            snapshot.slime.trader.@syncSKUBetweenTraders(updatedTrader.ouid, updatedTrader.account_ouid).resolve(updatedTrader).pipe(this);

                        }).pipe(this);

                    }
                })
            })

        },
        /**
         * @api {jsonrpc} slime@trader.resetTraderPassword(form)=result slime@trader.resetTraderPassword
         * @apiDescription 重置经销商密码
         * @apiGroup slime
         * @apiParam (form) {String} id 经销商id
         * @apiParam (form) {String} password 经销商新密码
         * @apiSuccess {Object} result 经销商信息
         */
        resetTraderPassword: function(session, { id, password }) {

            if (!session.currentOU) {
                throw @lab.errors.not_login;
            }

            return lab.find("slime_traders", id).then(function(trader) {

                if (!password) {
                    throw @lab.errors.invalid_parameters;
                }

                if (trader && trader.ouid == session.currentOU.id && trader.account_id) {

                    lab.snapshot(function(snapshot) {

                        return snapshot.find("backend_operators", trader.account_id).then(function(account) {

                            if (account) {
                                snapshot.backend.user.@updatePasswordByID(account.id, password).pipe(this);
                            } else {
                                throw @lab.errors.object_not_found;
                            }

                        });

                    }).resolve(trader).pipe(this);

                } else {
                    throw @lab.errors.object_not_found;
                }
            })
        },
        /**
         * @api {jsonrpc} slime@trader.updateTrader(form)=result slime@trader.updateTrader
         * @apiDescription 更新经销商信息
         * @apiGroup slime
         * @apiParam (form) {String} id 经销商id
         * @apiParam (form) {String} number 经销商编号
         * @apiParam (form) {String} name 经销商姓名
         * @apiParam (form) {String} area 经销商所在地区
         * @apiParam (form) {String} address 经销商办公地址
         * @apiParam (form) {String} contact 联系人
         * @apiParam (form) {String} phone 联系电话
         *
         * @apiSuccess {Object} result 经销商信息
         * @apiUse TypeDefineTrader
         */
        updateTrader: function(session, { id, number, name, area, address, contact, phone }) {

            if (!session.currentOU) {
                throw @lab.errors.not_login;
            }

            return lab.snapshot(function(snapshot) {

                return snapshot.find("slime_traders", id).then(function(trader) {

                    if (trader && !trader.is_removed && trader.ouid == session.currentOU.id) {

                        let traderInfo = {
                            trader_name: name,
                            trader_area: area,
                            trader_address: address,
                            trader_number: number,
                            trader_contact: contact,
                            trader_contact_phone: phone
                        }

                        snapshot.update("slime_traders", trader, traderInfo).pipe(this);

                    } else {
                        throw @lab.errors.object_not_found;
                    }
                })
            })

        },
        /**
         * @api {jsonrpc} slime@trader.deleteTrader(form)=result slime@trader.deleteTrader
         * @apiDescription 刪除经销商
         * @apiGroup slime
         * @apiParam (form) {String} id 经销商id
         *
         * @apiSuccess {Object} result 所删除经销商信息
         */
        deleteTrader: function(session, id) {

            if (!session.currentOU) {
                throw @lab.errors.not_login;
            }

            return lab.snapshot(function(snapshot) {

                return snapshot.find("slime_traders", id).then(function(trader) {

                    if (trader && !trader.is_removed ) {

                        @.async(function() {

                            snapshot.update("slime_traders", result.records[0], {
                                is_removed: true,
                                last_update: Date.now()
                            }).pipe(this);

                        }).then(function() {

                            snapshot.slime.trader.@syncSKUAfterTraderRemoved(trader).pipe(this);

                        }).pipe(this);

                    } else {
                        throw @lab.errors.object_not_found;
                    }
                })
            })

        },
        /**
         * @api {jsonrpc} slime@trader.searchParentTraders(form)=result slime@trader.searchParentTraders
         * @apiDescription 搜索上级经销商信息
         * @apiGroup slime
         * @apiParam (form) {String} keyword 经销商姓名或经销商编号
         * @apiParam (form) {Number} [start=0] 分页开始
         * @apiParam (form) {Number} [limit=10] 分页最大
         * @apiSuccess {Object} result 经销商信息
         * @apiUse TypeDefineTrader
         */
        searchParentTraders : function(session, {start, limit, keyword}) {

            if (!session.currentOU) {
                throw @lab.errors.not_login;
            }

            var condition = ["is_removed = ?", "account_ouid = ?"];
            var params = [false, session.currentOU.id];

            if (keyword) {
                condition.push("(trader_name like ? or trader_number like ?)");
                params.push("%" + keyword + "%", "%" + keyword + "%");
            }

            return lab.query("slime_traders", {
                "conditions": condition,
                "params": params,
                "start": start,
                "limit": limit
            })
        },
        /**
         * @api {jsonrpc} slime@trader.searchTraders(form)=result slime@trader.searchTraders
         * @apiDescription 搜索经销商信息
         * @apiGroup slime
         * @apiParam (form) {String} keyword 经销商姓名或经销商编号
         * @apiParam (form) {String} area 经销商所在地区
         *
         * @apiSuccess {Object} result 经销商信息
         * @apiUse TypeDefineTrader
         */
        searchTraders: function(session, { start, limit, keyword, account_ouid, area }) {

            if (!session.currentOU) {
                throw @lab.errors.not_login;
            }

            var condition = ["is_removed = ?"];
            var params = [false];

            if (account_ouid) {
                condition.push("ouid = ?");
                params.push(account_ouid);
            } else {
                condition.push("ouid = ?");
                params.push(session.currentOU.id);
            }

            if (area) {
                condition.push("trader_area = ?");
                params.push(area);
            }

            if (keyword) {
                condition.push("(trader_name like ? or trader_number like ?)");
                params.push("%" + keyword + "%", "%" + keyword + "%");
            }

            return lab.query("slime_traders", {
                "conditions": condition,
                "params": params,
                "start": start,
                "limit": limit
            })
        },
        /**
         * @api {jsonrpc} slime@trader.getTrader(form)=result slime@trader.getTrader
         * @apiDescription 获取经销商信息
         * @apiGroup slime
         * @apiParam (form) {String} id 经销商id
         *
         * @apiSuccess {Object} result 经销商信息
         * @apiUse TypeDefineTrader
         */
        getTrader: function(session, id) {

            if (!session.currentOU) {
                throw @lab.errors.not_login;
            }

            return lab.find("slime_traders", id).then(function(trader) {

                if (trader) {

                    if (trader.ouid == session.currentOU.id) {
                        this.next(trader);
                    } else {
                        throw @lab.errors.no_permission;
                    }

                } else {
                    throw @lab.errors.object_not_found;
                }

            });
        },

        // WynnREADME : 以后尽量对于输入性质的参数（非对象）， 采用在参数表中inline申明包含字段的方式
        @saveOrUpdateAccount: function(trader, { name, account, password }) {

            //1. 判定当前账号是否存在
            //2. 判断当前账号的ouid是否和当前用户一致
            //3. 判定当前账号是否已经绑定了一个trader，并且这个trader的ID和待更新trader的ID是否一致

            if (account && password) {

                return lab.snapshot(function(snapshot) {

                    return @.async(function() {

                        snapshot.sqlite.find("backend_operators", {
                            "account": account
                        }).pipe(this);

                    }).then(function(result) {

                        if (result.records.length) {
                            // 表示已经存在账号
                            var existing_account = result.records[0];

                            if (trader.account_id == existing_account.id) {

                                // 说明该经销商账号和登陆账号一致， 那就修改密码即可
                                snapshot.backend.user.@updatePasswordByID(existing_account.id, password).resolve(existing_account).pipe(this);

                            } else if (!trader.account_id) {

                                // 两者账号不一致的情况， 看目标账号是否存在已绑定过的经销商
                                snapshot.sqlite.find("slime_traders", {
                                    account_id: existing_account.id
                                }).then(function(result) {

                                    if (result.records.length) {
                                        throw @lab.errors.account_already_bind_trader;
                                    } else {
                                        // 这里要检查密码是否一致
                                        snapshot.backend.user.@checkPasswordByID(existing_account.id, password).resolve(existing_account).pipe(this);
                                    }

                                }).pipe(this);

                            } else {
                                throw @lab.errors.trader_already_bind_account;
                            }


                        } else {
                            // 创建新用户
                            snapshot.backend.users.@register({ name, account, password, ou_name: name, ou_type: "trader" }).then(function(result) {
                                this.next(result.user);
                            }).pipe(this);
                        }

                    });

                });

            } else {
                return @.async.resolve();
            }
        },

        @syncSKUAfterTraderRemoved : function(trader){

            return lab.snapshot(function(snapshot){

                return snapshot.sqlite.find("slime_trader_skus", {
                    "ouid"        : trader.account_ouid,
                    "source_ouid" : trader.id
                }).then(function(result) {

                    if (result.records.length) {

                        @.async.all(result.records, function(sku) {

                            snapshot.update("slime_trader_skus", sku, {
                                is_removed: true,
                                last_update: Date.now()
                            }).pipe(this);

                        }).pipe(this)

                    } else {
                        this.next();
                    }

                })
            })
        },
        // 一级经销商向二级经销商同步SKU
        @syncSKUBetweenTraders: function(traderOUID, subTraderOUID) {

            // 找出当前的OUID中的SKU

            return lab.snapshot(function(snapshot) {

                return @.async(function() {
                    // 一级经销商的sku
                    snapshot.sqlite.find("slime_trader_skus", {
                        "ouid": traderOUID
                    }).pipe(this);

                }).then(function(result) {

                    // 保存一级经销商的sku
                    this.pool.parent_skus = result.records;
                    // 找出一级经销商与二级经销商关联的所有sku
                    snapshot.sqlite.find("slime_trader_skus", {
                        "ouid": subTraderOUID,
                        "source_ouid": traderOUID,
                        "!": ["source_id != ?",null]
                    }).pipe(this);

                }).then(function(result) {

                    var subSKUMap = {};
                    // 查询出来的结果进行遍历 并且每条sku与自己的source_id组成一个map
                    result.records.forEach(function(sku) {
                        subSKUMap[sku.source_id] = sku;
                    });

                    // 我当前一级经销商的SKU
                    // 遍历一级经销商的sku ，通过sku中的id(即二级经销商sku source_id) 是否存在刚保存的map中 存在就更新 不存在就创建
                    @.async.all(this.pool.parent_skus, function(sku) {

                        if (subSKUMap[sku.id]) {

                            snapshot.update("slime_trader_skus", subSKUMap[sku.id], @.merge.simple(sku, {
                                id: subSKUMap[sku.id].id,
                                source_id: sku.source_id,
                                source_ouid: traderOUID,
                                ouid: subTraderOUID,
                                on_sale: subSKUMap[sku.id].on_sale
                            })).pipe(this);

                        } else {

                            snapshot.create("slime_trader_skus", @.merge.simple(sku, {
                                id: @.uuid(),
                                source_id: sku.source_id,
                                source_ouid: traderOUID,
                                ouid: subTraderOUID
                            })).pipe(this);

                        }

                    }).pipe(this);
                });
            })
        }

    }
}
